package com.sensePlusVR.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sensePlusVR.activity.follow.FollowDetailActivity;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.ActorItem;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.CollectionFollowManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressLint({ "UseSparseArrays", "HandlerLeak" })
public class FollowAllAdapter extends RecyclerView.Adapter<FollowAllAdapter.ViewHolders>{
	private static final String TAG = FollowAllAdapter.class.getSimpleName();
	private List<ActorItem> followAllList;
	private Context context;
	private DataCenter dataCenter;
	private Map<Integer, ViewHolders> holderMaps = new HashMap<Integer, ViewHolders>();

	public static final String KEY = FollowAllAdapter.class.getSimpleName();
	
	private MyHandler handler;
	
	EventListener listener = new EventListener(){

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (Params == null || data == null)
				return;
			if (event == CollectionFollowManager.EventFollowAdded ||
				event == CollectionFollowManager.EventFollowDeled ||
				(event-CollectionFollowManager.EventErrorBase) == CollectionFollowManager.EventFollowAdded ||
				(event-CollectionFollowManager.EventErrorBase) == CollectionFollowManager.EventFollowDeled)
				updateFollowList(event, (Integer)data);

		}
	};
	
	@SuppressWarnings("unused")
	private boolean listContainsOne(List<ActorItem> list, int actorId)
	{
		if (getIndex(list, actorId) < 0)
			return false;
		return true;
	}
	void updateFollowList(final int event, final Integer actorId){
		MyLog.d(TAG, "EventFollowCollectionGot id : " + actorId);
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				MyLog.d(TAG, "follow event="+event);
				if (event == CollectionFollowManager.EventFollowAdded){
				}else if (event == CollectionFollowManager.EventFollowDeled){
				}else if (event >= CollectionFollowManager.EventErrorBase) {
					int errEvent = event;
					errEvent -= CollectionFollowManager.EventErrorBase;
					if (errEvent == CollectionFollowManager.EventFollowAdded){
					}else if (errEvent == CollectionFollowManager.EventFollowDeled) {
					}
				}
				ActorItem itemCur = dataCenter.getActorById(actorId);
				if(itemCur == null)return;
					MyLog.d(TAG, "itemCur : " + itemCur.toString());
					int position = getIndex(followAllList,itemCur.getId());
					if (position >= 0) {
						followAllList.set(position, itemCur);
						notifyItemChanged(position);
					}
			}
		});
	}
	
	private int getIndex(List<ActorItem> list, int actorId){
		for (int i = 0; i < list.size(); i++){
			ActorItem item = list.get(i);
			if (item.getId() == actorId){
				return i;
			}
		}
		return -1;
	}
	
	 
	public FollowAllAdapter(Context context, List<ActorItem> followAllList) {
		this.context = context;
		this.followAllList = followAllList;
		dataCenter = DataCenter.getInstans();
		MyLog.d(TAG, "followAllList size : " + followAllList);
		
		handler = new MyHandler();
		
	}
	
	public class MyHandler extends Handler{
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg != null && msg.what == FollowDetailActivity.MSG_ACTIVITY_FULLY_DISPLAY && msg.obj.equals(KEY)){
				MyLog.d(TAG, "handle notify...");
				notifyDataSetChanged();
			}
		}
	}

	@Override
	public int getItemCount() {
		return followAllList.size();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public ViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_follow_all_item, parent, false);
		MyLog.d(TAG, "onCreateViewHolder....");
		return new ViewHolders(view);
	}

	@Override
	public void onBindViewHolder(final ViewHolders holder, int position) {
		ActorItem actorItem = followAllList.get(position);
		MyLog.d(TAG, "onBindViewHolder position : " + position);
		MyLog.d(TAG, "onBindViewHolder actorItem : " + actorItem.toString());
		
		int followCount = actorItem.getUserfollowcount() < 0?0:actorItem.getUserfollowcount();
		
		holder.follow_all_consequence.setText(actorItem.getName());
		holder.follow_all_plus_tv.setText(String.valueOf(followCount));
		holder.setActorId(actorItem.getId());
		holder.setMyPosition(position);

		String imageUrl = actorItem.getImgurl();
		MyLog.d(TAG, "imageUrl :" + imageUrl);
		
		holder.follow_all_cover_default_iv.setVisibility(View.VISIBLE);
		holder.follow_all_cover_iv.setVisibility(View.INVISIBLE);
		holder.follow_all_cover_default_iv.setImageResource(R.drawable.loadng_icon);
		ImageLibrary.getInstance().getImageBitmap(context, imageUrl, new Callback() {

			@Override
			public void onImageDownloaded(Bitmap bitmap) {
				MyLog.d(TAG, "bitmap : " + bitmap);
				if (bitmap != null){
					holder.follow_all_cover_default_iv.setVisibility(View.INVISIBLE);
					holder.follow_all_cover_iv.setVisibility(View.VISIBLE);
					holder.follow_all_cover_iv.setImageBitmap(bitmap);
				}
			}
		});
		if (actorItem.getFollowed() == 0){
			MyLog.e(TAG, "no followed");
			holder.follow_all_plus_iv.setImageResource(R.drawable.lovers_list_page_follow_icon);
		}else{
			MyLog.e(TAG, "followed");
			holder.follow_all_plus_iv.setImageResource(R.drawable.lovers_list_page_follow_icon_press);
		}
		
		String createTime = actorItem.getCreatetime();
		createTime = DateTimeUtil.removeZoneTime(createTime);
		if(DateTimeUtil.isLessPreviousMonth(createTime)){
			holder.follow_all_new_iv.setVisibility(View.VISIBLE);
		}else{
			holder.follow_all_new_iv.setVisibility(View.INVISIBLE);
		}
		
		List<GameItem> actorGameList = dataCenter.getGameListByActorName(actorItem.getName(), false,true);
		if(actorGameList != null && actorGameList.size() > 0){
			GameItem gameItemFirst = actorGameList.get(0);
			String createTimeInner = gameItemFirst.getCreatetime();
			
			createTimeInner = DateTimeUtil.removeZoneTime(createTimeInner);
			
			 boolean isFisrtClick = MySharedPreferences.getBoolean(context, String.valueOf(actorItem.getId()));
			if(DateTimeUtil.isLessPreviousMonth(createTimeInner) && !isFisrtClick){
				//显示红点
				holder.follow_all_redcircle_iv.setVisibility(View.VISIBLE);
				VRApplication.handlers.put(KEY, handler);
			}else{
				//隐藏红点
				holder.follow_all_redcircle_iv.setVisibility(View.GONE);
			}
			
		}
	}
	
	
	public void onResume(){
		dataCenter.addFCEventListener(listener, this, KEY);
	}
	
	
	public void onPause(){
		dataCenter.addFCEventListener(null, this, KEY);
	}
	
	public class MyOnClickListener implements View.OnClickListener {
		private ViewHolders holder;
		private ActorItem item;
		private int position;

		public MyOnClickListener(ViewHolders holder) {
			this.holder = holder;
		}

		@Override
		public void onClick(View v) {
			this.position = holder.getMyPosition();
			this.item = followAllList.get(position);
			MyLog.d(TAG, "onClick position : " + position);
			switch (v.getId()) {
			//详情
			case R.id.follow_all_fram:
				MyLog.d(TAG, "follow_all_fram is click..." + position);
				MyPageJump.pageJumpAddObject(context, FollowDetailActivity.class, item, Constant.FROM_FOLLOW_ALL);	
				
				break;
			//添加关注
			/*case R.id.follow_all_plus_linear:
				MyLog.d(TAG, "follow_all_plus_linear is click..." + position);
				if (item.getFollowed() == 0)
					dataCenter.FollowActorAdd(item.getId());
				//else
				//	dataCenter.FollowActorDel(item.getId());
				break;*/
			}
		}
	}
	

	class ViewHolders extends RecyclerView.ViewHolder {
		public FrameLayout follow_all_fram;
		public ImageView follow_all_cover_default_iv;
		public ImageView follow_all_cover_iv;
		public ImageView follow_all_new_iv;
		public ImageView follow_all_redcircle_iv;
		public TextView follow_all_consequence;
		//public LinearLayout follow_all_plus_linear;
		public ImageView follow_all_plus_iv;
		public TextView follow_all_plus_tv;
		public int actorId;
		public int getActorId() {
			return actorId;
		}

		public void setActorId(int actorId) {
			this.actorId = actorId;
		}

		public int getMyPosition() {
			return myPosition;
		}

		public void setMyPosition(int myPosition) {
			this.myPosition = myPosition;
		}

		public int myPosition;
		
		public ViewHolders(View itemView) {
			super(itemView);
			follow_all_fram = (FrameLayout) itemView.findViewById(R.id.follow_all_fram);
			follow_all_cover_default_iv = (ImageView) itemView.findViewById(R.id.follow_all_cover_default_iv);
			follow_all_cover_iv = (ImageView) itemView.findViewById(R.id.follow_all_cover_iv);
			follow_all_new_iv = (ImageView) itemView.findViewById(R.id.follow_all_new_iv);
			follow_all_redcircle_iv = (ImageView) itemView.findViewById(R.id.follow_all_redcircle_iv);
			follow_all_consequence = (TextView) itemView.findViewById(R.id.follow_all_consequence);
			//follow_all_plus_linear = (LinearLayout) itemView.findViewById(R.id.follow_all_plus_linear);
			follow_all_plus_iv = (ImageView) itemView.findViewById(R.id.follow_all_plus_iv);
			follow_all_plus_tv = (TextView) itemView.findViewById(R.id.follow_all_plus_tv);

			follow_all_fram.setOnClickListener(new MyOnClickListener(this));
			//follow_all_plus_linear.setOnClickListener(new MyOnClickListener(this));
			
			//动态设置View高度，避免某类手机对图片压缩问题，使得图片始终保持4：5
			LayoutParams lp = follow_all_fram.getLayoutParams();
			int gapDP = (context.getResources().getDimensionPixelSize(R.dimen.padding_left_unify_follow_recycler)*2
					+ context.getResources().getDimensionPixelSize(R.dimen.padding_follow_all)*4);
			
			lp.height = (int) ((DensityUtil.getScreenWidth(context) - gapDP) / 2 * 1.25);
			follow_all_fram.setLayoutParams(lp);

		}
	}

	/**
	 * 批量更新数据
	 * 
	 * @param followFollowList
	 */
	public void refreshData() {
		notifyDataSetChanged();
	}

	/**
	 * 单个更新数据
	 * 
	 * @param item
	 */
	public void add(ActorItem item) {
		followAllList.add(item);
		notifyItemInserted(followAllList.size() - 1);
	}

	@Override
	public void onViewAttachedToWindow(ViewHolders holder) {
		super.onViewAttachedToWindow(holder);
		holderMaps.put(holder.getActorId(), holder);
	}

	@Override
	public void onViewDetachedFromWindow(ViewHolders holder) {
		super.onViewDetachedFromWindow(holder);
		holderMaps.remove(holder.getActorId());
	}
}
